﻿using GKQC.Common;
using GKQC.DbHelper.DbModels;
using GKQC.DbHelper.Services;
using System;using GKQC.Language;
using System.Diagnostics;
using System.IO.Ports;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using System.Collections.Generic;
using System.ComponentModel;
using GKQC.DbHelper.ViewModels;

namespace GKQC.Machine
{
    public partial class FormComSet : Form
    {
        XmlNode _LcrNode = null;
        XmlNode _LcNode = null;
        XmlNode _CaliperNode = null;

        XmlNode _Lc10Node = null;
        XmlNode _BoxNode = null;
        XmlNode _BoxNode2 = null;
        UserModel _User = null;

        XmlNode _MachinesNode = null;
        List<MachineSet> _Machines = new List<MachineSet>();

        bool _IsTestting = false;
        
        /// <summary>
        /// 是否全自動測試
        /// </summary>
        XmlNode _IsAllAutoNode = null;
        public FormComSet(UserModel user)
        {
            InitializeComponent(); LanguageHelper.SetControlLanguageText(this);

            this._User = user;

            //获取可用串口列表;
            cboLcrCom.Items.Add(string.Empty);
            cboLcCom.Items.Add(string.Empty);
            cboCaliperCom.Items.Add(string.Empty);
            cboLc10Com.Items.Add(string.Empty);
            cboBoxCom.Items.Add(string.Empty);
            cboBoxCom2.Items.Add(string.Empty);

            GetCom();
            
            if (cboLcrCom.Items.Count > 0)
            {
                cboLcrCom.SelectedIndex = 0;
            }
            if (cboLcCom.Items.Count > 0)
            {
                cboLcCom.SelectedIndex = 0;
            }
            if (cboCaliperCom.Items.Count > 0)
            {
                cboCaliperCom.SelectedIndex = 0;
            }
            if (cboLc10Com.Items.Count > 0)
            {
                cboLc10Com.SelectedIndex = 0;
            }
            if (cboBoxCom.Items.Count > 0)
            {
                cboBoxCom.SelectedIndex = 0;
            }
            if (cboBoxCom2.Items.Count > 0)
            {
                cboBoxCom2.SelectedIndex = 0;
            }

            cboLcrType.Items.AddRange(Enum.GetNames(typeof(Settings.LcrType)));
            cboLcType.Items.AddRange(Enum.GetNames(typeof(Settings.LcType)));

            cboLcrBaudRate.SelectedIndex = 0;
            cboLcBaudRate.SelectedIndex = 0;
            cboCaliperBaudRate.SelectedIndex = 0;
            cboLcrType.SelectedIndex = 0;
            cboLc10BaudRate.SelectedIndex = 0;
            cboBoxBaudRate.SelectedIndex = 0;
            cboBoxBaudRate2.SelectedIndex = 0;

            _LcrNode = Settings.GetLcrComXmlNode();
            _LcNode = Settings.GetLcComXmlNode();
            _CaliperNode = Settings.GetCaliperComXmlNode();
            _Lc10Node = Settings.GetLc10ComXmlNode();
            _BoxNode = Settings.GetBoxComXmlNode();
            _BoxNode2 = Settings.GetBoxCom2XmlNode();
            _IsAllAutoNode = Settings.GetIsAllAutoXmlNode();
            _MachinesNode = Settings.GetMachinesXmlNode();

            InitGridCombbBox();

            ReadSetting();

            dataGridView1.DataSource = new BindingList<MachineSet>(_Machines);
        }

        void InitGridCombbBox()
        {
            //设备类型
            try
            {
                string propertyName = ColMachineType.DataPropertyName;
                var machinetypes = MachineSet.GetMachineType<BaseDataView>();
                ColMachineType.DataPropertyName = string.Empty;
                ColMachineType.DataSource = new BindingList<BaseDataView>(machinetypes);
                ColMachineType.ValueType = typeof(BaseDataView);
                ColMachineType.DisplayMember = "Name";
                ColMachineType.ValueMember = "Code";
                ColMachineType.DataPropertyName = propertyName;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }

            //串口
            try
            {
                List<BaseDataView> ports = new List<BaseDataView>();
                foreach (string s in _ports)
                {
                    BaseDataView v = new BaseDataView();
                    v.Code = s;
                    v.Name = s;
                    ports.Add(v);
                }
                string propertyName = ColPortName.DataPropertyName;
                ColPortName.DataPropertyName = string.Empty;
                ColPortName.DataSource = new BindingList<BaseDataView>(ports);
                ColPortName.ValueType = typeof(BaseDataView);
                ColPortName.DisplayMember = "Name";
                ColPortName.ValueMember = "Code";
                ColPortName.DataPropertyName = propertyName;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }

            //波特率
            try
            {
                List<BaseDataView> BaudRates = MachineSet.GetBaudRate<BaseDataView>();
                string propertyName = ColBaudRate.DataPropertyName;
                ColBaudRate.DataPropertyName = string.Empty;
                ColBaudRate.DataSource = new BindingList<BaseDataView>(BaudRates);
                ColBaudRate.ValueType = typeof(BaseDataView);
                ColBaudRate.DisplayMember = "Name";
                ColBaudRate.ValueMember = "Id";
                ColBaudRate.DataPropertyName = propertyName;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }

        List<string> _ports = new List<string>();
        void GetCom()
        {
            string[] ports = SerialPort.GetPortNames();
            foreach (string port in ports)
            {
                if (!_ports.Contains(port)) _ports.Add(port);

                if (!cboLcrCom.Items.Contains(port))
                cboLcrCom.Items.Add(port);
                if (!cboLcCom.Items.Contains(port))
                    cboLcCom.Items.Add(port);
                if (!cboCaliperCom.Items.Contains(port))
                    cboCaliperCom.Items.Add(port);
                if (!cboLc10Com.Items.Contains(port))
                    cboLc10Com.Items.Add(port);
                if (!cboBoxCom.Items.Contains(port))
                    cboBoxCom.Items.Add(port);
                if (!cboBoxCom2.Items.Contains(port))
                    cboBoxCom2.Items.Add(port);
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (!this.Validate()) return;

            if (_LcrNode != null)
            {
                if (cboLcrCom.SelectedItem != null && cboLcrCom.SelectedItem != null)
                    _LcrNode.SelectSingleNode("ComName").InnerText = cboLcrCom.SelectedItem.ToString();
                if (cboLcrBaudRate.SelectedItem != null && cboLcrBaudRate.SelectedItem != null)
                    _LcrNode.SelectSingleNode("BaudRate").InnerText = cboLcrBaudRate.SelectedItem.ToString();
                if (cboLcrType.SelectedItem != null && cboLcrType.SelectedItem != null)
                    _LcrNode.SelectSingleNode("LcrType").InnerText = cboLcrType.SelectedItem.ToString();
            }
            if (_LcNode != null)
            {
                if (cboLcCom.SelectedItem != null && cboLcCom.SelectedItem!= null)
                    _LcNode.SelectSingleNode("ComName").InnerText = cboLcCom.SelectedItem.ToString();
                if (cboLcrBaudRate.SelectedItem != null && cboLcBaudRate.SelectedItem != null)
                    _LcNode.SelectSingleNode("BaudRate").InnerText = cboLcBaudRate.SelectedItem.ToString();
                if (cboLcType.SelectedItem != null && cboLcType.SelectedItem != null)
                    _LcNode.SelectSingleNode("LcType").InnerText = cboLcType.SelectedItem.ToString();
            }
            if (_CaliperNode != null)
            {
                if (cboLcrCom.SelectedItem != null && cboCaliperCom.SelectedItem != null)
                    _CaliperNode.SelectSingleNode("ComName").InnerText = cboCaliperCom.SelectedItem.ToString();
                if (cboLcrBaudRate.SelectedItem != null && cboCaliperBaudRate.SelectedItem != null)
                    _CaliperNode.SelectSingleNode("BaudRate").InnerText = cboCaliperBaudRate.SelectedItem.ToString();
            }
            if (_Lc10Node != null)
            {
                if (cboLc10Com.SelectedItem != null && cboLc10Com.SelectedItem != null)
                    _Lc10Node.SelectSingleNode("ComName").InnerText = cboLc10Com.SelectedItem.ToString();
                if (cboLc10BaudRate.SelectedItem != null && cboLc10BaudRate.SelectedItem != null)
                    _Lc10Node.SelectSingleNode("BaudRate").InnerText = cboLc10BaudRate.SelectedItem.ToString();
            }
            if (_BoxNode != null)
            {
                if (cboBoxCom.SelectedItem != null && cboBoxCom.SelectedItem != null)
                    _BoxNode.SelectSingleNode("ComName").InnerText = cboBoxCom.SelectedItem.ToString();
                if (cboBoxBaudRate.SelectedItem != null && cboBoxBaudRate.SelectedItem != null)
                    _BoxNode.SelectSingleNode("BaudRate").InnerText = cboBoxBaudRate.SelectedItem.ToString();
            }
            if (_BoxNode2 != null)
            {
                if (cboBoxCom2.SelectedItem != null && cboBoxCom2.SelectedItem != null)
                    _BoxNode2.SelectSingleNode("ComName").InnerText = cboBoxCom2.SelectedItem.ToString();
                if (cboBoxBaudRate2.SelectedItem != null && cboBoxBaudRate2.SelectedItem != null)
                    _BoxNode2.SelectSingleNode("BaudRate").InnerText = cboBoxBaudRate2.SelectedItem.ToString();
            }
            if (_IsAllAutoNode != null)
            {
                _IsAllAutoNode.InnerText = chkIsAllAuto.Checked ? "true" : "false";
            }

            if (_MachinesNode != null)
            {
                _MachinesNode.InnerText = _Machines.ToJson();
            }

            try
            {
                string file = Settings.GetSettingFileName();
                _LcrNode.OwnerDocument.Save(file);
                QMessageBox.Show("保存成功","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                this.Close();
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message,"異常S0150", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void ReadSetting()
        {
            if (_LcrNode != null)
            {
                string comName = _LcrNode.SelectSingleNode("ComName").InnerText;
                if (cboLcrCom.Items.Count == 0 && !string.IsNullOrWhiteSpace(comName))
                    cboLcrCom.Items.Add(comName);
                cboLcrCom.SelectedIndex = cboLcrCom.Items.IndexOf(comName);
                cboLcrBaudRate.SelectedIndex = cboLcrBaudRate.Items.IndexOf(_LcrNode.SelectSingleNode("BaudRate").InnerText);
                cboLcrType.SelectedIndex = cboLcrType.Items.IndexOf(_LcrNode.SelectSingleNode("LcrType").InnerText);
            }

            if (_LcNode != null)
            {
                string comName = _LcNode.SelectSingleNode("ComName").InnerText;
                if (cboLcCom.Items.Count == 0 && !string.IsNullOrWhiteSpace(comName))
                    cboLcCom.Items.Add(comName);
                cboLcCom.SelectedIndex = cboLcCom.Items.IndexOf(comName);
                cboLcBaudRate.SelectedIndex = cboLcBaudRate.Items.IndexOf(_LcNode.SelectSingleNode("BaudRate").InnerText);
                cboLcType.SelectedIndex = cboLcType.Items.IndexOf(_LcNode.SelectSingleNode("LcType").InnerText);
            }

            if (_CaliperNode != null)
            {
                string comName = _CaliperNode.SelectSingleNode("ComName").InnerText;
                if (cboCaliperCom.Items.Count == 0 && !string.IsNullOrWhiteSpace(comName))
                    cboCaliperCom.Items.Add(comName);
                cboCaliperCom.SelectedIndex = cboCaliperCom.Items.IndexOf(comName);
                cboCaliperBaudRate.SelectedIndex = cboCaliperBaudRate.Items.IndexOf(_CaliperNode.SelectSingleNode("BaudRate").InnerText);

            }

            if (_Lc10Node != null)
            {
                string comName = _Lc10Node.SelectSingleNode("ComName").InnerText;
                if (cboLc10Com.Items.Count == 0 && !string.IsNullOrWhiteSpace(comName))
                    cboLc10Com.Items.Add(comName);
                cboLc10Com.SelectedIndex = cboLc10Com.Items.IndexOf(comName);
                cboLc10BaudRate.SelectedIndex = cboLc10BaudRate.Items.IndexOf(_Lc10Node.SelectSingleNode("BaudRate").InnerText);
            }

            if (_BoxNode != null)
            {
                string comName = _BoxNode.SelectSingleNode("ComName").InnerText;
                if (cboBoxCom.Items.Count == 0 && !string.IsNullOrWhiteSpace(comName))
                    cboBoxCom.Items.Add(comName);
                cboBoxCom.SelectedIndex = cboBoxCom.Items.IndexOf(comName);
                cboBoxBaudRate.SelectedIndex = cboBoxBaudRate.Items.IndexOf(_BoxNode.SelectSingleNode("BaudRate").InnerText);
            }
            if (_BoxNode2 != null)
            {
                string comName = _BoxNode2.SelectSingleNode("ComName").InnerText;
                if (cboBoxCom2.Items.Count == 0 && !string.IsNullOrWhiteSpace(comName))
                    cboBoxCom2.Items.Add(comName);
                cboBoxCom2.SelectedIndex = cboBoxCom2.Items.IndexOf(comName);
                cboBoxBaudRate2.SelectedIndex = cboBoxBaudRate2.Items.IndexOf(_BoxNode2.SelectSingleNode("BaudRate").InnerText);
            }

            if (_IsAllAutoNode != null) //是否全自动测试
            {
                string auto = _IsAllAutoNode.InnerText;
                bool isAllAuto = false;
                bool.TryParse(auto, out isAllAuto);
                chkIsAllAuto.Checked = isAllAuto;
            }

            if (_MachinesNode != null)
            {
                string machines = _MachinesNode.InnerText;
                if (!string.IsNullOrWhiteSpace(machines))
                {
                    List<MachineSet> ms = machines.ToObject<List<MachineSet>>();
                    if (ms != null && ms.Count > 0)
                        _Machines.AddRange(ms);

                    foreach (var m in _Machines)
                    {
                        if (!_ports.Contains(m.PortName))
                            _ports.Add(m.PortName);
                    }
                }
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FormComSet_FormClosing(object sender, FormClosingEventArgs e)
        {
        }

        private void btnShort_Click(object sender, EventArgs e)
        {
            if (_IsTestting) return;
            try
            {
                this.Cursor = Cursors.WaitCursor;
                _IsTestting = true;
                SerialPort sp = new SerialPort();
                Settings.GetPortBuad(sp, Settings.MachineType.LCR);
                sp.Open();
                Thread.Sleep(200);
                ILcrMeter lcrMeter = MachineFactory.GetLcrMeter();
                lcrMeter.Short(sp);

                Stopwatch sw = new Stopwatch();
                sw.Start();
                while(true)
                {
                    Thread.Sleep(3000);
                    string resutl = lcrMeter.GetData(sp);
                    if (resutl.Contains("OK")) break;
                    if (sw.Elapsed.TotalSeconds > 120) break;
                }

                sp.Close();
                Thread.Sleep(300);
                sp = null;

                QMessageBox.Show("短路校正完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message,"異常S0082",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
            finally
            {
                _IsTestting = false;
                this.Cursor = Cursors.Default;
            }
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (_IsTestting) return;
            try
            {
                this.Cursor = Cursors.WaitCursor;
                _IsTestting = true;
                SerialPort sp = new SerialPort();
                Settings.GetPortBuad(sp, Settings.MachineType.LCR);
                sp.Open();
                Thread.Sleep(200);
                ILcrMeter lcrMeter = MachineFactory.GetLcrMeter();
                lcrMeter.Open(sp);

                Stopwatch sw = new Stopwatch();
                sw.Start();
                while (true)
                {
                    Thread.Sleep(3000);
                    string resutl = lcrMeter.GetData(sp);
                    if (resutl.Contains("OK")) break;
                    if (sw.Elapsed.TotalSeconds > 120) break;
                }

                sp.Close();
                Thread.Sleep(300);
                sp = null;

                QMessageBox.Show("開路校正完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0083", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                _IsTestting = false;
                this.Cursor = Cursors.Default;
            }
        }

        private void cboLcrCom_DropDown(object sender, EventArgs e)
        {
            GetCom();
        }

        private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        bool isBoxCom = false;
        private void tsmAutoSetCom_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                SerialPort sp = new SerialPort();
                var lcr = MachineFactory.GetLcrMeter();
                foreach (string com in cboLcrCom.Items)
                {
                    try
                    {
                        if (string.IsNullOrWhiteSpace(com)) continue;
                        if (sp.IsOpen) sp.Close();
                        sp.PortName = com;
                        int rate = 19200;
                        int.TryParse(cboLcrBaudRate.SelectedItem.ToString(), out rate);
                        sp.BaudRate = rate;
                        sp.Open();
                        Thread.Sleep(200);
                        if (lcr.Check(sp))
                        {
                            cboLcrCom.SelectedItem = com;
                            label1.BackColor = System.Drawing.Color.Green;
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError(ex);
                    }
                }
                if (sp.IsOpen) sp.Close();

                foreach (string com in cboBoxCom.Items)
                {
                    try
                    {
                        if (string.IsNullOrWhiteSpace(com)) continue;
                        isBoxCom = false;
                        if (sp.IsOpen) sp.Close();
                        sp.PortName = com;
                        int rate = 9600;
                        int.TryParse(cboBoxBaudRate.SelectedItem.ToString(), out rate);
                        sp.BaudRate = rate;
                        sp.Open();
                        sp.DiscardOutBuffer();
                        var box = new TestLeakApp.Box(sp, 0, ShowBoxMessage);
                        Thread.Sleep(200);
                        box.Check();
                        Thread.Sleep(500);
                        if (isBoxCom)
                        {
                            cboBoxCom.SelectedItem = com;
                            label11.BackColor = System.Drawing.Color.Green;
                            break;
                        }
                    }
                    catch(Exception ex)
                    {
                        Logger.LogError(ex);
                    }
                }
                if (sp.IsOpen) sp.Close();


                int count = 0;
                foreach (string com in cboBoxCom.Items)
                {
                    try
                    {
                        if (string.IsNullOrWhiteSpace(com)) continue;
                        isBoxCom = false;
                        if (sp.IsOpen) sp.Close();
                        sp.PortName = com;
                        int rate = 9600;
                        int.TryParse(cboBoxBaudRate2.SelectedItem.ToString(), out rate);
                        sp.BaudRate = rate;
                        sp.Open();
                        sp.DiscardOutBuffer();
                        var box = new TestLeakApp.Box(sp, 0, ShowBoxMessage);
                        Thread.Sleep(200);
                        box.Check();
                        Thread.Sleep(500);
                        if (isBoxCom)
                        {
                            count++;
                            if (count == 2)
                            {
                                cboBoxCom.SelectedItem = com;
                                label14.BackColor = System.Drawing.Color.Green;
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError(ex);
                    }
                }
                if (sp.IsOpen) sp.Close();

                string com1 = string.Empty;
                string com2 = string.Empty;
                try
                {
                    foreach (string com in cboLcCom.Items)
                    {
                        if (string.IsNullOrWhiteSpace(com)) continue;
                        if (sp.IsOpen) sp.Close();
                        sp.PortName = com;
                        int rate = 9600;
                        int.TryParse(cboLcBaudRate.SelectedItem.ToString(), out rate);
                        sp.BaudRate = rate;
                        sp.Open();
                        var lc = MachineFactory.GetLcMeter();
                        Thread.Sleep(200);
                        if (lc.Check(sp))
                        {
                            if (string.IsNullOrWhiteSpace(com1))
                                com1 = com;
                            else if (string.IsNullOrWhiteSpace(com2))
                                com2 = com;

                            if (!string.IsNullOrWhiteSpace(com1)
                                && !string.IsNullOrWhiteSpace(com2))
                                break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex);
                }

                if (!string.IsNullOrWhiteSpace(com1) || !string.IsNullOrWhiteSpace(com2))
                {
                    if (!string.IsNullOrWhiteSpace(com1) && !string.IsNullOrWhiteSpace(com2))
                    {
                        cboLcCom.SelectedItem = String.Compare(com1, com2, true) == 1 ? com2 : com1;
                        cboLc10Com.SelectedItem = String.Compare(com1, com2, true) == 1 ? com1 : com2;
                        label3.BackColor = System.Drawing.Color.Green;
                        label9.BackColor = System.Drawing.Color.Green;
                    }
                    else
                    {
                        cboLcCom.SelectedItem = string.IsNullOrWhiteSpace(com1) ? com2 : com1;
                        label3.BackColor = System.Drawing.Color.Green;
                    }
                }

                if (sp.IsOpen) sp.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
                MessageBox.Show("设置完成");
            }
        }

        void ShowBoxMessage(string msg)
        {
            if(!string.IsNullOrWhiteSpace(msg))
            Logger.LogMessage("Box Check:" + msg);

            if (msg.Contains("00 80 01 AA 2B 0D 0A"))
                isBoxCom = true;
        }

        private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if(dataGridView1.Columns[e.ColumnIndex] == ColMachineType)
                {
                    
                }
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }
    }
}
